package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class My_Profile_Buy extends ListActivity {
	// List is a linked list
	// Map is a hash table: String -> Object
	private List<Map<String, Object>> mData;
	final Bundle extras = new Bundle();
	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_profile_buy_main);
		String[] usernamePassword = LoginUtility.getUsernamePassword(My_Profile_Buy.this);
		String username = usernamePassword[0];
		showDialog(SPINNER);
		progThread = new ProgressThread(mhandler,username);
		progThread.start();
	}

	private List<Map<String, Object>> getData(String data) {
		List< Map<String, Object> > list = new ArrayList< Map<String, Object> >();
		
		Map<String, Object> map = new HashMap<String, Object>();
		try{
		    JSONArray jArray = new JSONArray(data);
		    JSONObject json_data=null;
		    int length = jArray.length();
		    for(int i = 0; i < length; i++){
		    json_data = jArray.getJSONObject(i);
		    map = new HashMap<String, Object>();
			map.put("title", json_data.getString("Title"));
			map.put("edition", json_data.getString("Edition"));
			map.put("courses", json_data.getString("Courses"));
			map.put("authors", json_data.getString("Authors"));
			map.put("publishers", json_data.getString("Publisher"));
			map.put("ISBN", json_data.getString("ISBN"));
			map.put("bought", json_data.getString("Date"));
			map.put("status", json_data.getString("Status"));
			map.put("ID", json_data.getString("CopyID"));
			map.put("Condition", json_data.getString("Condition"));
			map.put("Price", json_data.getString("Price"));
			list.add(map);
		    }
		}catch (JSONException e) {
            throw new RuntimeException(e);
        }

		return list;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}
	
	final Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			
			if(returnedData.contains("error")){
				Toast.makeText(My_Profile_Buy.this, "Network Error", Toast.LENGTH_SHORT).show();
			}
			else{
				mData = getData(returnedData);
				
				MyAdapter adapter = new MyAdapter(My_Profile_Buy.this);
				setListAdapter(adapter);
			}
		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		String username;

		ProgressThread(Handler h, String u) {
			mHandler = h;
			username = u;
		}

		@Override
		public void run() {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", username));
			String returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/buy_borrow_history_display.jsp");
			
			Message msg = mHandler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("returnedData", returnedData);
			msg.setData(b);
			mHandler.sendMessage(msg);
		}

		// Set current state of thread (use state=ProgressThread.DONE to stop
		// thread)

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		// Log.v("MyListView4-click", (String)mData.get(position).get("title"));
		/*Intent myIntent = new Intent(this,
				ViewBookDetailsTab.class);
		myIntent.putExtra("title", (String) mData.get(position).get("title"));
		myIntent.putExtra("edition", (String) mData.get(position)
				.get("edition"));
		myIntent.putExtra("course", (String) mData.get(position)
				.get("course"));
		myIntent.putExtra("authors", (String) mData.get(position)
				.get("authors"));
		myIntent.putExtra("publishers",
				(String) mData.get(position).get("publishers"));
		myIntent.putExtra("ISBN", (String) mData.get(position).get("ISBN"));
		startActivity(myIntent);*/
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private ViewHolder holder = null;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}


		public int getCount() {
			return mData.size();
		}


		public Object getItem(int arg0) {
			return null;
		}


		public long getItemId(int arg0) {
			return 0;
		}

		public final class ViewHolder {
			public TextView title;
			public TextView edition;
			public TextView course;
			public TextView authors;
			public TextView publishers;
			public TextView ISBN;
			public TextView bought;
			public Button sellLend;
			public int position;
		}


		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.my_profile_buy, null);
				holder.title = (TextView) convertView.findViewById(R.id.tv_MyProfileBuy_title);
				holder.edition = (TextView) convertView
						.findViewById(R.id.tv_MyProfileBuy_edition);
				holder.course = (TextView) convertView
						.findViewById(R.id.tv_MyProfileBuy_course);
				holder.authors = (TextView) convertView
						.findViewById(R.id.tv_MyProfileBuy_authors);
				holder.publishers = (TextView) convertView
						.findViewById(R.id.tv_MyProfileBuy_publishers);
				holder.ISBN = (TextView) convertView.findViewById(R.id.tv_MyProfileBuy_ISBN);
				holder.bought = (TextView) convertView
						.findViewById(R.id.tv_MyProfileBuy_bought);
				holder.sellLend = (Button) convertView.findViewById(R.id.b_MyProfileBuy_sellLend);
				holder.position = position;
				
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.title.setText((String) mData.get(position).get("title"));
			holder.edition.setText("Edition: "+(String) mData.get(position).get("edition"));
			if((String) mData.get(position).get("course") == null)
				holder.course.setText("Courses: N/A");
			else
				holder.course.setText("Courses: " + (String) mData.get(position).get("course"));
			if((String) mData.get(position).get("authors") == null)
				holder.authors.setText("Authors: N/A");
			else
				holder.authors.setText("Authors: " + (String) mData.get(position).get("authors"));
			if((String) mData.get(position).get("publishers") == null)
				holder.publishers.setText("Publishers: N/A");
			else
				holder.publishers.setText("Publishers: " + (String) mData.get(position).get(
					"publishers"));
			holder.ISBN.setText("ISBN: " + (String) mData.get(position).get("ISBN"));
			
			holder.sellLend.setTag(position);
			
			//Log.v("position",Integer.toString(holder.position));
			if(((String)mData.get(position).get("status")).contains("User Side")){
				holder.bought.setText("Borrowed on: " + (String) mData.get(position).get("bought"));
				holder.sellLend.setVisibility(LinearLayout.GONE);
			}
			else if(((String)mData.get(position).get("status")).contains("Canceled")){
				holder.bought.setText("Bought on: " + (String) mData.get(position).get("bought"));
				holder.sellLend.setVisibility(LinearLayout.GONE);
			}
			else{
				holder.bought.setText("Bought on: " + (String) mData.get(position).get("bought"));
				holder.sellLend.setOnClickListener(new OnClickListener() {		
	
					public void onClick(View v) {
						// TODO Auto-generated method stub
						int position = Integer.parseInt(v.getTag().toString() );
						Intent myIntent = new Intent(My_Profile_Buy.this,
								SellLend_Confirm.class);
						myIntent.putExtra("modify", true);
						myIntent.putExtra("type","buy-resell");
						myIntent.putExtra("condition", (String) mData.get(position).get("Condition"));
						myIntent.putExtra("price", (String) mData.get(position).get("Price"));
						myIntent.putExtra("copyid", (String) mData.get(position).get("ID"));
						
						myIntent.putExtra("title", (String) mData.get(position).get("title"));
						myIntent.putExtra("authors", (String) mData.get(position).get("authors"));
						myIntent.putExtra("ISBN", (String) mData.get(position).get("ISBN"));
						myIntent.putExtra("publishers", (String) mData.get(position).get("publishers"));
						myIntent.putExtra("edition", (String) mData.get(position).get("edition"));
						myIntent.putExtra("courses", (String) mData.get(position).get("course"));
						startActivity(myIntent);
						
					}
				});
			}
			return convertView;
		}

	}


}
